package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.*;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.FansVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CountsApi countsApi;

    @DubboReference
    private FriendsApi friendsApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;


    //保存用户信息
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new RuntimeException("不包含人脸");
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo userInfoVo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, userInfoVo);//copy同名同类型的属性

        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }

        return userInfoVo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //互相喜欢，喜欢，粉丝 - 统计
    public Counts findCounts() {
        Counts count = countsApi.getCount(UserHolder.getUserId());
        return count;
    }

    //修改手机号 - 2 校验验证码
    public boolean checkVerificationCode(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            boolean a = false;
            //验证码无效
            throw new RuntimeException("验证码错误");
        }
        boolean a = true;
        return a;
    }

    //修改手机号 - 3 保存
    public void savePhone(Long userId, String phone) {
        userInfoApi.savePhone(userId, phone);

    }

    //1 获取互相喜欢
    public PageResult findfriend(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        //page的计算规则
        List<UserLike> list = friendsApi.queryfriendsList(page, pagesize, userId);
        //5、提取列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);

        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<FansVo> cos = new ArrayList<>();
        int counts = list.size();
        for (UserLike like : list) {
            UserInfo info = map.get(like.getUserId());
            if (info != null) {
                FansVo co = FansVo.init(info);
                cos.add(co);
            }
        }
        return new PageResult(page, pagesize, Long.valueOf(counts), cos);
    }

    //2我关注 -翻页列表
    public PageResult findMyloves(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        //page的计算规则
        List<UserLike> list = friendsApi.queryLovesList(page, pagesize, userId);
        //5、提取列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "likeUserId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<FansVo> cos = new ArrayList<>();
        int counts = list.size();
        for (UserLike like : list) {
            UserInfo info = map.get(like.getLikeUserId());
            if (info != null) {
                FansVo co = FansVo.init(info);
                cos.add(co);
            }
        }

        return new PageResult(page, pagesize, Long.valueOf(counts), cos);
    }


    //3粉丝 -翻页列表
    public PageResult findFans(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        UserLike userLike = new UserLike();
        //page的计算规则
        List<UserLike> list = friendsApi.queryFansList(page, pagesize, userId);
        int counts = list.size();
        //5、提取列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<FansVo> cos = new ArrayList<>();
        for (UserLike like : list) {
            UserInfo info = map.get(like.getUserId());
            if (info != null) {
                FansVo co = FansVo.init(info);
                co.setAlreadyLove(userLike.getIsLike());
                cos.add(co);
            }
        }
        return new PageResult(page, pagesize, Long.valueOf(counts), cos);
    }

    //喜欢粉丝
    public void fansLike(Long userId, Long uid) {
        boolean exists = friendsApi.fansLike(userId, uid);
        if (exists) {
            throw new RuntimeException("已经喜欢粉丝");
        }
        //环信有问题
        /*//1、将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + uid);
        if(!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }*/
        //2、如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(),uid);
    }

    //取消喜欢粉丝
    public void fansUnlike(Long userId, Long uid) {
        boolean exists = friendsApi.findFriends(userId,uid);
        if (!exists){
            throw new RuntimeException("已经取消喜欢粉丝");
        }
        friendsApi.deleteFriend(userId,uid);
    }
}
